package pers.xx.sbm.service.serviceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import pers.xx.sbm.dao.MenuMapper;
import pers.xx.sbm.entity.Menu;
import pers.xx.sbm.service.MenuService;
import pers.xx.sbm.utils.MenuUtils;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author ：xiexing
 * @description：TODO
 * @date ：2020/8/12 12:50
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl implements MenuService {

    MenuMapper menuMapper;

    @Autowired
    RedisTemplate redisTemplate;

    public MenuServiceImpl(@Autowired MenuMapper menuMapper) {
        super.dao = menuMapper;
        this.menuMapper = menuMapper;
    }

    /**
     * @description 获取封装菜单
     * @author XieXing
     * @date 2020/8/12 22:06
     */
    @Override
    public List<Menu> getWrapMenus(Menu menu) {
        List<Menu> menus = menuMapper.getListSelective(menu);
        return MenuUtils.buildMenuTree(menus, 0);//0表示顶级菜单
    }

    /**
     * @description 根据角色id获取菜单并且判断菜单是否被选中
     * @author XieXing
     * @date 2020/9/17 22:07
     */
    @Override
    public List<Menu> getMenusWithChecked(Integer roleId) {
        List<Menu> menus = menuMapper.getListWithCheckedStatus(roleId);
        return MenuUtils.buildMenuTree(menus, 0);//0表示顶级菜单
    }

    @Override
    public List<Menu> getMenuByUserId(Integer userId, Integer navId) {
        ValueOperations<String, List<Menu>> valueOperations = redisTemplate.opsForValue();
        List<Menu> menus = valueOperations.get("menus");
        if (menus == null) { //将获取的菜单添加至redis缓存（系统菜单更新记得刷新redis缓存）
            menus = menuMapper.getMenuByUserId(userId);
            valueOperations.set("menus", menus);
        }
        return MenuUtils.buildMenuTree(menus, navId);
    }

    /**
     * @description 获取导航
     * @author XieXing
     * @date 2020/12/9 16:46
     */
    @Override
    public List<Menu> getNavs() {
        return menuMapper.getNavs();
    }

    /**
     * @description 获取用户权限
     * @author XieXing
     * @date 2021/1/8 17:15
     */
    @Override
    public Set<String> listUserPerms(Integer userId) {
        List<String> perms = menuMapper.listUserPerms(userId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms) {
            if (!StringUtils.isEmpty(perm)) {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

}
